﻿using System;
using System.Collections.Generic;
using DB;
using ViewModel;

namespace Logic
{
    /// <summary>
    /// SampleDBのLogicクラス
    /// </summary>
    public class SampleDBLogic
    {
        #region 定数
        /// <summary>取得用SQLファイル</summary>
        private const string SELECT_TABLE = @"DB.SQL.Select_T_SAMPLE.sql";
        /// <summary>追加用SQLファイル</summary>
        private const string INSERT_TABLE = @"DB.SQL.Insert_T_SAMPLE.sql";

        #endregion

        #region public
        /// <summary>
        /// データを取得する
        /// </summary>
        /// <returns></returns>
        public List<GridData> GetData()
        {
            List<GridData> gridDataList = new List<GridData>();

            string[] columns = new string[] { "ID", "UPDATE_TIME", "CONTENTS" };
            // データを読み取る
            var tb = DBLogic.ExecuteReader(SELECT_TABLE, columns);

            if (tb == null || tb.Rows == null || tb.Rows.Count <= 0) 
            {
                return gridDataList;
            }

            // GridDataに格納する
            for (int rowIdx = 0; rowIdx < tb.Rows.Count; rowIdx++)
            {
                int id;
                int.TryParse(tb.Rows[rowIdx]["ID"] as string ?? String.Empty, out id);
                DateTime upd;
                DateTime.TryParse(tb.Rows[rowIdx]["UPDATE_TIME"] as string ?? String.Empty, out upd);
                var contents = tb.Rows[rowIdx]["CONTENTS"] as string;
                gridDataList.Add(new GridData() { ID = id, Contents = contents, UpdateTime = upd });
            }

            return gridDataList;
        }

        /// <summary>
        /// DBに登録する
        /// </summary>
        /// <param name="contents">コンテンツ</param>
        public void Regist(string contents)
        {
            // パラメータ
            Dictionary<string, object> paramDic = new Dictionary<string, object>();
            paramDic.Add("CONTENTS", contents);
            paramDic.Add("UPDATE_TIME", DateTime.Now);

            // SQL実行
            DBLogic.ExecuteNonQuery(INSERT_TABLE, paramDic);
        }

        #endregion
    }
}
